<?php

namespace app\command\once;

use think\console\Command;
use think\console\Input;
use think\console\Output;

class SynchronizeAnchor extends Command{
	
	protected function configure()
	{
		// 指令配置
		$this->setName('SynchronizeAnchor')->addArgument('partition_id')->setDescription('主播历史数据同步');
	}
	
	protected function execute(Input $input, Output $output)
	{
		//同步主播数据
		$partitionId= $input->getArgument('partition_id')??'';
		if($partitionId===""){
			echo("分区号不能为空\n");
            return false;
		}
		//获取分区数据
		$partitionCurInfo=\app\common\model\common\PartitionPackage::where([
			'partition_id'=>$partitionId,
			'status'=>1
		])->find();
		if(empty($partitionCurInfo->id)){
			echo("分区ID无效，请重试\n");
			return false;
		}
		//连接子库
        $subCurMemberModel=getSwitchDatabaseModel(
			sprintf("partition_%s",$partitionCurInfo['partition_id']),
			$partitionCurInfo['api_mysql_host_name'],
			$partitionCurInfo['api_mysql_database'],
			$partitionCurInfo['api_mysql_username'],
			$partitionCurInfo['api_mysql_password'],
			$partitionCurInfo['api_mysql_hostport']
		);
		//初始化ID
		$curId=0;
		$limitNum=100;
		$totalNum=$subCurMemberModel->table('member')->where('mobile','<>','')->where('status','in',[1,3])->count()?:0;
		echo(sprintf("分区号：%s-查询到主播数据：%s 个\n",$partitionId,$totalNum));
		$totalAnbleNum=0;
		//查询全部未注销的主播用户
		while(true){
			//获取目前
			$lists=$subCurMemberModel->table('member')->where('mobile','<>','')->where('status','in',[1,3])->where('id','>',$curId)->order('id','asc')->limit($limitNum)->column('mobile','id')?:[];
			if(empty($lists)){
				echo(sprintf("用户数据同步已执行结束-同步主播总数量：%s\n",$totalAnbleNum));
				return false;
			}
			$ids=array_keys($lists);
			$mobiles=array_values($lists);
			//获取最大ID数据作为下次轮询
			$curId=max($ids);
			//检测主表中该手机号是否存在，不存在则新增
			$anchorMobiles=\app\common\model\common\Anchor::where('mobile','in',$mobiles)->where('status','=',1)->column('mobile')?:[];
			//获取差异化数组
			$diffMobiles=array_values(array_diff($mobiles,$anchorMobiles));
			//检测测试号数据
			$memberIds=$subCurMemberModel->table('anchor_test_account')->where('member_id','in',$ids)->column('member_id')?:[];
			$testMobiles=$subCurMemberModel->table('member')->where('id','in',$memberIds)->column('mobile')?:[];
			//拼装入库数据
			$inserts=[];
			foreach($diffMobiles as $diffMobile){
				$inserts[]=[
					'mobile'		=>$diffMobile,
					'partition_id'	=>$partitionId,
					'is_test'		=>in_array($diffMobile,$testMobiles)?1:0,
					'create_time'	=>time(),
					'update_time'	=>time(),
				];
			}
			$totalAnbleNum+=count($inserts);
			//主播主库数据存储
			$ret=(new \app\common\model\common\Anchor())->insertAll($inserts);
			echo(sprintf("用户数据同步中-本次同步主播数量：%s；同步保存状态：%s\n",$totalAnbleNum,(int)$ret));
		}

	}
	
}
